#!/bin/bash

# 设置颜色输出
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
NC='\033[0m' # No Color

# 获取项目根目录
PROJECT_ROOT=$(cd "$(dirname "$0")/../.." && pwd)
FRONTEND_DIR="$PROJECT_ROOT/mcphub-frontend-vue3"
BACKEND_DIR="$PROJECT_ROOT/mcphub-backend-django"
DOCS_DIR="$PROJECT_ROOT/mcphub-docs-vitepress"
DEPLOY_DIR="$PROJECT_ROOT/mcphub-scripts/deploy"

echo -e "${GREEN}==== MCPRepoMarket 一键部署脚本 ====${NC}"
echo -e "${YELLOW}项目根目录: $PROJECT_ROOT${NC}"

# 检查必要的工具
echo -e "\n${GREEN}检查必要工具...${NC}"
command -v node >/dev/null 2>&1 || { echo -e "${YELLOW}需要安装 Node.js${NC}"; exit 1; }
command -v npm >/dev/null 2>&1 || { echo -e "${YELLOW}需要安装 npm${NC}"; exit 1; }
command -v python3 >/dev/null 2>&1 || { echo -e "${YELLOW}需要安装 Python3${NC}"; exit 1; }
command -v pip >/dev/null 2>&1 || { echo -e "${YELLOW}需要安装 pip${NC}"; exit 1; }
command -v nginx >/dev/null 2>&1 || { echo -e "${YELLOW}需要安装 Nginx${NC}"; exit 1; }

# 创建日志和部署目录
mkdir -p "$DEPLOY_DIR/logs"
mkdir -p "$DEPLOY_DIR/dist"

# 部署前端
echo -e "\n${GREEN}部署前端...${NC}"
cd "$FRONTEND_DIR" || exit 1
npm install
npm run build
cp -r dist/* "$DEPLOY_DIR/dist/frontend/"
echo -e "${GREEN}前端部署完成${NC}"

# 部署文档
echo -e "\n${GREEN}部署文档...${NC}"
cd "$DOCS_DIR" || exit 1
npm install
npm run build
cp -r .vitepress/dist/* "$DEPLOY_DIR/dist/docs/"
echo -e "${GREEN}文档部署完成${NC}"

# 部署后端
echo -e "\n${GREEN}部署后端...${NC}"
cd "$BACKEND_DIR" || exit 1
# 创建虚拟环境
python3 -m venv venv
source venv/bin/activate
pip install -r requirements.txt

# 初始化数据库和静态文件
python manage.py migrate
python manage.py collectstatic --noinput

# 导入MCP列表数据
echo -e "${GREEN}导入MCP SERVER列表数据...${NC}"
python manage.py import_mcp_list "$PROJECT_ROOT/mcphub-scripts/mcp-server-list-tools/mcp-list-merged.json"

echo -e "${GREEN}后端部署完成${NC}"

# 配置Nginx
echo -e "\n${GREEN}配置Nginx...${NC}"
sudo cp "$DEPLOY_DIR/mcphub.conf" /etc/nginx/sites-available/
sudo ln -sf /etc/nginx/sites-available/mcphub.conf /etc/nginx/sites-enabled/
sudo nginx -t && sudo systemctl restart nginx
echo -e "${GREEN}Nginx配置完成${NC}"

echo -e "\n${GREEN}部署完成！${NC}"
echo -e "你可以使用 ./start.sh 启动所有服务" 